//
//  CategoriesViewController.m
//  TimeTracker
//
//  Created by Michael Flakus on 3/2/13.
//  Copyright (c) 2013 Michael Flakus. All rights reserved.
//

#import "CategoriesViewController.h"
#import "CategoryCell.h"
#import "CategoryDetailViewController.h"

@interface CategoriesViewController ()

@end

@implementation CategoriesViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Categories";
}

-(void)viewWillAppear:(BOOL)animated
{
    [self loadCategories];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return _categoryIDs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"categoryTableCell";
    CategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    
    int row = [indexPath row];
    
    cell.categoryNameLabel.text = _categoryNames[row];
    
    return cell;
}



#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}





- (void)loadCategories
{
    // load data from database
    _categoryIDs = [[NSMutableArray alloc] init];
    _categoryNames = [[NSMutableArray alloc] init];
    
    
    // database lookups
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            // load all active activities
            NSString *select_categories = [NSString stringWithFormat:@"SELECT categories.id, categories.name from categories where categories.active = 1 order by name"];
            const char *select_categories_const = [select_categories UTF8String];
            
            sqlite3_stmt *res_categories;
            if(sqlite3_prepare(_database, select_categories_const, -1, &res_categories, NULL) != SQLITE_OK)
            {
                NSLog(@"Problem with prepare statement: %s",select_categories_const);
                NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
            }
            else
            {
                while (sqlite3_step(res_categories)==SQLITE_ROW) {
                    
                    //NSLog(@"Found a category");
                    [_categoryIDs addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,0)]];
                    [_categoryNames addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_categories,1)]];
                    
                }
                sqlite3_finalize(res_categories);
            }
        }
        else
        {
            NSLog(@"Error: database could not be found in CategoryViewController");
        }
    }
    
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
    
}


// functions for deleting
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	// Do not allow rows to be deleted when in editing mode.
	return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"row selected to be deleted: %d",[indexPath row]);
    
    // database lookups
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            char *errMsg;
            
            // TODO: check to make sure category is not assigned to activities
            // possible solutions: display alert to user OR assign activities to special "Uncategorized" category that cannot be deleted
            
            // delete category
            NSString *delete_sql = [NSString stringWithFormat:@"update categories set active = 0 where id = '%@'",_categoryIDs[[indexPath row]]];
            NSLog(@"delete query: %@",delete_sql);
            const char *delete_sql_const = [delete_sql UTF8String];
            if (sqlite3_exec(_database, delete_sql_const, NULL, NULL, &errMsg) != SQLITE_OK)
                NSLog(@"Failed: %s",errMsg);
        }
        else
        {
            NSLog(@"Error: database could not be found in CategoriesViewController");
        }
    }
    
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
    
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"editing is done... reload the table");
    [self loadCategories];
    [self.tableView reloadData];
}



-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"ShowCategoryDetails"])
    {
        CategoryDetailViewController *detailViewController = [segue destinationViewController];
        
        NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
        
        int row = [myIndexPath row];
        
        NSLog(@"selected cat: %@",_categoryNames[row]);
        
        detailViewController.categoryDetailModel = @[_categoryIDs[row],_categoryNames[row]];
    }
}




@end
